from gevent import pywsgi, monkey

monkey.patch_all()
import logging as rel_log

from werkzeug.debug import DebuggedApplication
from datetime import timedelta

from flask import *
from flask_socketio import SocketIO, emit, join_room, leave_room

from core import run_main, Run

app = Flask(__name__)
app.secret_key = 'secret!'
socketio = SocketIO(app)
werkzeug_logger = rel_log.getLogger('werkzeug')
werkzeug_logger.setLevel(rel_log.ERROR)

# 解决缓存刷新问题
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)

# 添加header解决跨域
@app.after_request
def after_request(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Allow-Methods'] = 'POST'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, X-Requested-With'
    return response


@app.route('/')
def hello_world():
    return redirect(url_for('static', filename='./editor/index.html'))


@app.route('/submit', methods=['POST'])
def receive_code():
    writed_code = request.json['code']
    print(writed_code)
    status = run_main.run(writed_code)
    return str(status)


# flask-socketio并不基于flask上下文，在其他地方调用下面的函数会有各种奇怪问题
# （如跨域问题） 所以所有websocket代码都要写在下面的socketio.on上下文里，写在
# 下面的函数里
@socketio.on('run')
def print_log(_):
    m = Run.Run_once()
    # 队列传入run.main中
    run_main.get_instance(m)
    while True:
        get = m.queue.get()
        if get == 0:
            break
        else:
            emit('print_log', {'data': get['log']})
    emit('print_log', {'data': '运行结束'})


# @socketio.on('event')
# def print_log(info):
#     # 发送 由客户端的server_response事件接受
#     emit('print_log', {'data': info})


if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5001, debug=True, log_output=False)
    # app.run(host='0.0.0.0', port=5001, debug=True)
    # dapp = DebuggedApplication(app, evalex=True)
    # server = pywsgi.WSGIServer(('', 5000), dapp)
    # server.serve_forever()
